﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BiocityFilmquizAdmin.Src.Domain;
using MySql.Data.MySqlClient;
using BiocityFilmquizAdmin.Src.Security;
using BiocityFilmquizAdmin.Src.Mail;

namespace BiocityFilmquizAdmin.Src.DatabaseAccess
{
    public class UserHelper
    {
        private DbAcces dbAccess;
        private static UserHelper instance = null;

        private UserHelper()
        {
            dbAccess = DbAcces.getInstance();
        }

        public static UserHelper getInstance()
        {
            if (instance == null)
            {
                instance = new UserHelper();
            }

            return instance;
        }

        public User getUser(String userName)
        {
            String query = "SELECT * FROM users WHERE userName = '" + userName + "';";

            MySqlDataReader reader = dbAccess.Select(query);

            string name = null;
            string email = null;
            int userId = 0;
            bool admin = false;

            if (reader.HasRows)
            {
                reader.Read();
                name = reader.GetString(1);
                email = reader.GetString(3);
                userId = reader.GetInt32(0);
                admin = reader.GetBoolean(4);
            }

            dbAccess.CloseConnection();
            reader.Close();

            User newUser = new User();

            if(name != null)
            {
                newUser.name = name;
                newUser.email = email;
                newUser.userID = userId;
                newUser.admin = admin;
            }
            else
            {
                newUser = null;
            }
            
            if (newUser != null && !newUser.admin)
            {
                query = "SELECT * FROM answers WHERE user = " + newUser.userID + " and round = " + Statics.getInstance().getCurrentRound() + ";";

                reader = dbAccess.Select(query);

                while (reader.Read())
                {
                    newUser.setQuestionTrueArray(reader.GetInt32(1));
                }
                reader.Close();
                dbAccess.CloseConnection();
            }
            else if (newUser != null && newUser.admin)
            {
                for (int i = 1; i <= Statics.getInstance().getNumberOfQuestions(); i++)
                {
                    newUser.setQuestionTrueArray(i);
                }
            }

            return newUser;
        }

        public User getUserByIdAndName(string userName, int userId)
        {
            String query = "SELECT * FROM users WHERE userName = '" + userName + "' AND userId = " + userId + ";";

            MySqlDataReader reader = dbAccess.Select(query);
            bool check = reader.HasRows;
            dbAccess.CloseConnection();
            reader.Close();

            if (check)
            {
                return getUser(userName);
            }
            else
            {
                return null;
            }
        }

        public Boolean saveUser(User user, String password)
        {
            bool succes = createUser(user.name, password, user.email);

            return succes;
        }


        public bool checkLogin(string userName, string password)
        {
            String query = "SELECT * FROM users WHERE userName = '" + userName + "' AND password = '" + PasswordProtection.EncodePassword(password) + "';";

            MySqlDataReader reader = dbAccess.Select(query);
            bool check = reader.HasRows;
            dbAccess.CloseConnection();
            reader.Close();
            return check;
        }

        public bool createUser(String userName, String password, String email)
        {
            String query = "INSERT INTO users (userName, password, email) VALUES('" + userName + "', '" + PasswordProtection.EncodePassword(password) + "', '" + email + "');";
            dbAccess.Insert(query);

            return checkLogin(userName, password);
        }

        public void playerCompleted(int user)
        {
            String query = "INSERT INTO playersCompleted (user, round) VALUES (" + user + ", " + Statics.getInstance().getCurrentRound() + ");";

            dbAccess.Insert(query);
        }

        /// <summary>
        /// Method that returns username and password for at user with the provided email.
        /// Returns a List, with username in first place and password in second.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public string getUsernameByEmail(string email)
        {
            string query = "select * from users where email = '" + email + "';";
            MySqlDataReader reader = dbAccess.Select(query);
            bool found = reader.Read();
            string username;
            if (found)
            {
                username = reader.GetString(1);
            }
            else
            {
                return null;
            }

            dbAccess.CloseConnection();

            return username;
        }

        public void saveNewPassword(User user, string password)
        {

            string query = "update users set password = '" + PasswordProtection.EncodePassword(password) + "' where userID = " + user.userID + ";";

            dbAccess.Update(query);
        }

        public void sendNewPassword(string email)
        {
            string username = getUsernameByEmail(email);
            string newPassword = PasswordProtection.generatePassword();

            User user = getUser(username);

            saveNewPassword(user, newPassword);

            MailHelper.getInstance().sendUsernameAndNewPassword(email, username, newPassword);
        }
    }

}